/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  ScrollView,
  TouchableOpacity,
  TouchableHighlight,
  ToolbarAndroid,
  Dimensions,
  BackHandler,
  Platform,
  ListView,
  PixelRatio,
} from 'react-native';

import Common from '../../component/common';
import ScreenUtils from '../../component/ScreenUtils';
import ToolbarComponent from '../../component/ToolbarComponent';

import SubscriptionItem from '../me/part/subscriptionItem';
import InfoItem from '../me/part/infoItem';
import VarietyItem from '../me/part/varietyItem';

import Loading from '../../component/loading';
import LoadError from '../../component/loadError';

const wechat=require('../../images/wechat.png');
const weibo=require('../../images/weibo.png');
const web=require('../../images/newspaper.png');

import BriefIntroduction from '../specialColumn/briefIntroduction';
import ColumnDetails from '../specialColumn/columnDetails';

export default class infoSearch extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
    	dataSource: new ListView.DataSource({
        	rowHasChanged: (row1, row2) => row1 !== row2,
      	}),
      	keywords: this.props.did,
      	loading: true,
		success: false,
      	nowpage:1,
      	pagesize:12,
      	footer:0,
      	error:false,
      	noMoreData:false,
    };
    this.fetchData = this.fetchData.bind(this);
    this.totalList = [];
  }
  
  componentWillMount() {  
    if (Platform.OS === 'android') {  
      BackHandler.addEventListener('hardwareBackPress',() => Common.onBack(this));  
    }  
  }  
  componentWillUnmount() { 
  	this.timer && clearTimeout(this.timer); 
  	this.loadtimer1 && clearTimeout(this.loadtimer1);
  	this.loadtimer2 && clearTimeout(this.loadtimer2);
    if (Platform.OS === 'android') {  
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));  
    }  
  } 
  componentDidMount(){
  	this.fetchData();
  }
  fetchData(){
  	  this.setState({
  	  	loadingMoreData:false,
  	  });
	  let formData = new FormData();
	  	formData.append("keywords",this.state.keywords);
	  	formData.append("nowpage",this.state.nowpage);
	  	formData.append("pagesize",this.state.pagesize);
	    Common.fetchData("post", "/search/specialColumnList", formData, (resp) => {
        var responseData = Common.page("listResult", resp);
        this.totalList = this.totalList.concat(responseData.result);
	    	this.setState({
  				dataSource:this.state.dataSource.cloneWithRows(this.totalList),
  				nowpage:responseData.np+1,
  				dataLength:responseData.total,
  				totalPage:responseData.ap,
          noMoreData:responseData.noMoreData,
  				loading: false,
  				success: true,
  				loadingFail:false,
  				loadingMoreData:true,
  			})
	    },() => {
	      if(this.state.nowpage===1){
		      	this.setState({
					loading: false,
					success: false,
					errorMessage: "请求失败",
					loadingMoreData:true,
				})
		      }else{
		      	this.loadtimer1=setTimeout(() => {
		      		this.setState({
						loadingFail: true,
						loadingFailText:"加载失败，点我重新加载",
						loadingMoreData:true,
					})
		      	},500)
		    }
	    },() => {
		    if(this.state.nowpage===1){
		      	this.setState({
					loading: false,
					success: false,
					errorMessage: "网络错误",
					loadingMoreData:true,
				})
		      }else{
		      	this.loadtimer2=setTimeout(() => {
		      		this.setState({
						loadingFail: true,
						loadingFailText:"加载失败，点我重新加载",
						loadingMoreData:true,
					})
		      	},500)
		    }
	    });
  }
  _loadingMoreData(event){
  	if(!this.state.noMoreData && this.state.loadingMoreData){
  		this.fetchData();
  		
  	}
  }
  
  refreshData(){
  	this.setState({
  		loadingFailText:"加载中...."
  	})
  	this.loadingAgain = setTimeout(() => {
  		this.fetchData();

  	},1000)
  }
  
  renderListHeader(){
  	return(
  		<Text style={styles.collectionCategory}>
			<Text>共{String(this.state.dataLength)}条</Text>
		</Text>
  	)
  }
  renderListFooter(){
  	return(
  		<View>
	  		{
				this.state.noMoreData ? <View style={styles.noMoreData}><Text style={styles.noMoreDataText}>数据已全部加载完毕</Text></View>:null
			}
			{
				this.state.loadingFail ? <TouchableOpacity onPress = {this.refreshData.bind(this)} style={styles.noMoreData}><Text style={styles.noMoreDataText}>{this.state.loadingFailText}</Text></TouchableOpacity>:null
			}
		</View>
  	)
  }
  
 renderSubscription(data,sectionID,rowID) {
 	var mydata = Common.keyWordHighlight(data.specialColumnTitle);
 	var specialColumnSubject = Common.keyWordHighlight(data.specialColumnSubject);
 	var columnTitle = Common.cancelHightlight(data.specialColumnTitle);
    return (
	      <TouchableHighlight 
          underlayColor="#fafafa" 
          delayPressIn={100} 
	      	style ={styles.subItemContainer} 
	      	onPress={() => {
		      		if(parseInt(data.type)== 8){
		      			Common.onForward(this, BriefIntroduction,"", data.id);
		      		}else if(parseInt(data.type)== 9){
		      			Common.onForward(this, ColumnDetails,columnTitle, data.id,"","no","Normal","true");
		      		}
	      		}
	      	}
	      >
          <View style={{flex:1,flexDirection:"row"}}>
      			<View style={styles.subItemConWrap}>
      				<View style={styles.userAbout}>
      					<View style={styles.userImgWrap}>
      						{
      							data.userPic ?
      								<Image 
      									style={styles.userImg} 
      									source={{uri: data.userPic}} /> :
      								<Image style={styles.userImg} source = {require('../../images/me/User.png')}/>
      						}
      						
      					</View>
      					<View style={styles.userInfo}>
      						<Text style={styles.userName}>{data.userName}</Text>
      						<Text 
      							style={styles.userRanking}
      							numberOfLines = {2}
      						>
      							{data.userRank}
      						</Text>
      					</View>
      				</View>
      				<View style={styles.subItemAbout}>
      					<Text style={styles.subItemTitle} numberOfLines = {2}>
      						{
      				          	mydata.map((item,i)=>{
      				          		if(item.hightLight){
      				          			return(
      				          				<Text key={i} style={{color:"red"}}>{item.data}</Text>
      				          			)
      				          		}else{
      				          			return(
      				          				<Text key={i}>{item.data}</Text>
      				          			)
      				          		}
      				          	})
      			        	}
      					</Text>
      					<View style={styles.subMagazine}>
      						<Text style={styles.subMagazineText} numberOfLines = {2}>
      						
      							{
      					          	specialColumnSubject.map((item,i)=>{
      					          		if(item.hightLight){
      					          			return(
      					          				<Text key={i} style={{color:"red"}}>{item.data}</Text>
      					          			)
      					          		}else{
      					          			return(
      					          				<Text key={i}>{item.data}</Text>
      					          			)
      					          		}
      					          	})
      				        	}
      						</Text>
      					</View>
      				</View>
      			</View>
      			<View style={styles.subItemImgCon}>
      				<View style={styles.subItemImgWrap}>
      					{
      						data.specialColumnPic1 ?
      							<Image 
      								style={styles.subItemcoverImg} 
      								source={{uri: data.specialColumnPic1 }}
      							/> : <View style={[styles.subItemImgWrap,{borderWidth:1,borderColor:"#ededed"}]}><Text style={styles.noImg}>暂无图片</Text></View>
      					}
      					
      				</View>
      			</View>
          </View>
	      </TouchableHighlight>
    );
  }
  
  render() {
    return (
      <View style ={styles.subscriptionContainer}>
  	    <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this);
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>搜索结果 - 专栏</Text>
          </View>
        </ToolbarComponent>
		{
      		this.state.loading ?
				<Loading/>
					: (
						this.state.success ?
							<View style={{flex:1}}>
					      		<View style={styles.subscriptionItem}>
							      	<ListView
										dataSource={this.state.dataSource}
									    renderRow={this.renderSubscription.bind(this)}
									    enableEmptySections={true}
									    showsVerticalScrollIndicator ={false}
									    onEndReached={this._loadingMoreData.bind(this)}
									    onEndReachedThreshold={500}
									    renderHeader = {this.renderListHeader.bind(this)}
									    renderFooter = {this.renderListFooter.bind(this)}
									    scrollRenderAheadDistance = {300}
									    removeClippedSubviews ={true}
									/>
						      	</View>
					      	</View>
						    : <LoadError reload={this.fetchData} reason={this.state.errorMessage}/>
					)      		
      }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  subscriptionContainer:{
    flex: 1,
  	backgroundColor:"#f6f6f6",
  	flexDirection:"column",
  },
  subscriptionItem:{
  	//paddingBottom:ScreenUtils.scaleSize(14),
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: ScreenUtils.scaleSize(40),
  },
  subItemContainer:{
    width:Dimensions.get('window').width,
  	backgroundColor:"#fff",
  	flexDirection:"row",
  	height:ScreenUtils.scaleSize(330),
  	borderBottomWidth:1,
    borderTopWidth:1,
  	borderColor:"#ebebeb",
  	marginBottom:ScreenUtils.scaleSize(14),
  },
  subItemConWrap:{
  	flex:1,
  	flexDirection:"column",
  	marginBottom:ScreenUtils.scaleSize(42),
  	marginLeft:ScreenUtils.scaleSize(30),
  	paddingLeft:ScreenUtils.scaleSize(10),
  	paddingRight:ScreenUtils.scaleSize(10),
  },
  userAbout:{
  	height:ScreenUtils.scaleSize(130),
  	borderBottomWidth:1/PixelRatio.get(),
  	borderColor:"#d2d2d2",
  	flexDirection:"row",
  	alignItems:"center",
  },
  userImgWrap:{
  	width:ScreenUtils.scaleSize(76),
  	height:ScreenUtils.scaleSize(76),
  },
  userImg:{
  	width:ScreenUtils.scaleSize(76),
  	height:ScreenUtils.scaleSize(76),
  	borderRadius:ScreenUtils.scaleSize(76)/2,
  },
  userInfo:{
  	flex:1,
  	paddingLeft:ScreenUtils.scaleSize(26),
  	flexDirection:"column",
  	justifyContent:"center",
  },
  userName:{
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#000",
  },
  userRanking:{
  	fontSize:ScreenUtils.scaleSize(18),
  	color:"#939393",
  	lineHeight:Math.round(ScreenUtils.scaleSize(30)),
  },
  subItemAbout:{
  	flex:1,
  	flexDirection:"column",
  	justifyContent:"space-around",
  },
  subItemTitle:{
  	color:"#000",
  	fontSize:ScreenUtils.scaleSize(30),
  	paddingTop:ScreenUtils.scaleSize(5),
  },
  subMagazine:{
  	flexDirection:"row",
  },
  subMagazineText:{
  	fontSize:ScreenUtils.scaleSize(20),
  	color:"#939393",
  	marginBottom:ScreenUtils.scaleSize(5),
  	lineHeight:Math.round(ScreenUtils.scaleSize(30)),
  },
  subItemImgCon:{
  	width:ScreenUtils.scaleSize(225),
  	justifyContent:"center",
  	alignItems:"center",
  },
  subItemImgWrap:{
  	width:ScreenUtils.scaleSize(183),
  	height:ScreenUtils.scaleSize(246),
  	position:"relative",
  	justifyContent:"center",
  	alignItems:"center",
  },
  noImg:{
  	color:"#ededed",
  	fontSize:ScreenUtils.scaleSize(20),
  },
  subItemcoverImg:{
  	width:ScreenUtils.scaleSize(183),
  	height:ScreenUtils.scaleSize(246),
  },
  subItemStatus:{
  	position:"absolute",
  	right:0,
  	top:0,
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(54),
  },
  coverIcon:{
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(54),
  },
  subItemStatusText:{
  	position:"absolute",
  	right:0,
  	top:0,
  	width:ScreenUtils.scaleSize(54),
  	height:ScreenUtils.scaleSize(34),
  	textAlign:"center",
  	fontSize:ScreenUtils.scaleSize(12),
  	marginTop:ScreenUtils.scaleSize(10),
  	color:"#fff",
  },
  deleteWrap:{
  	width:ScreenUtils.scaleSize(132),
  	backgroundColor:"#ff4545",
  	justifyContent:"center",
  	alignItems:"center",
  	borderBottomWidth:1,
  	borderColor:"#ebebeb",
  },
  deleteText:{
  	fontSize:ScreenUtils.scaleSize(26),
  	color:"#fff",
  },
  collectionCategory:{
  	paddingLeft:ScreenUtils.scaleSize(30),
  	fontSize:ScreenUtils.scaleSize(24),
  	color:"#939393",
  	paddingBottom:ScreenUtils.scaleSize(14),
  	paddingTop:ScreenUtils.scaleSize(14),
  },
  Item:{
  	marginTop:ScreenUtils.scaleSize(10),
  	borderTopWidth:1,
  	borderColor:"#ededed",
  },
  showMore:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(78),
  	backgroundColor:'#fff',
  	borderBottomWidth:1,
  	borderColor:'#ebebeb',
  	flexDirection:"row",
  	marginTop:-ScreenUtils.scaleSize(14),
  	marginBottom:ScreenUtils.scaleSize(14),
  },
  noMoreData:{
  	flex:1,
  	justifyContent:"center",
  	alignItems:"center",
  	height:ScreenUtils.scaleSize(150),
  	flexDirection:"row",
  	marginTop:-ScreenUtils.scaleSize(14),
  },
  noMoreDataText:{
  	fontSize:ScreenUtils.scaleSize(18),
  }
});